<template>
  <section class="container" style="width: 60%">
    <div id="containerMap" />
    <div id="myPageTop">
      <div class="map-container">
        <div class="map-item1">
          <div class="map-title">按关键字搜索:</div>
          <input id="tipsinput">
        </div>
        <div class="map-item2">
          <div class="map-title">点击获取经纬度:</div>
          <input id="lnglat">
        </div>
      </div>
    </div>
  </section>
</template>

<script >
import AMapLoader from '@amap/amap-jsapi-loader'

// 文档链接 https://lbs.amap.com/api/jsapi-v2/guide/abc/prepare
window._AMapSecurityConfig = {
  securityJsCode: 'bca27b469a3ea657b4dae593073ac263'// 安全密钥
}

export default {
  name: 'GaodeMap',
  props: {
    value: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      map: '',
      marker: '',
      autoOptions: {
        input: 'tipsinput' // 搜索框id
      },
      placeSearch: null, // 存放实例
      geocoder: null, // 存放实例
      location: {
        lng: '',
        lat: '',
        address: ''
      }
    }
  },
  watch: {
  },
  mounted() {
    this.$nextTick(() => {
      this.handler().initMap()
    })
  },
  methods: {
    // 地图点击事件获取经纬度
    clickHandler(e) {
      const { lnglat } = e
      const {
        lat,
        lng
      } = lnglat || {}
      this.location.lng = lng
      this.location.lat = lat
      const value = (lat && lng) ? `${lng},${lat}` : ''
      document.getElementById('lnglat').value = value
      this.geocoder.getAddress([lng, lat], this.getChangeAddress)
    },
    // 监听关键字查询
    mapSelect(e) {
      console.log('监听关键字查询', e)
      const {
        lat,
        lng
      } = e.poi.location || {}
      const value = (lat && lng) ? `${lng},${lat}` : ''
      document.getElementById('lnglat').value = value
      this.location.lng = lng
      this.location.lat = lat
      const { name, district } = e.poi
      const mergeVal = `${district}${name}`
      const address = name.includes("市") ? name : mergeVal
      this.$nextTick(() => {
        document.getElementById('tipsinput').value = `${address}`
      })
      this.location.address = address
      this.placeSearch.setCity(e.poi.adcode)
      this.placeSearch.search(e.poi.name) // 关键字查询查询
      this.$emit('input', this.location)
    },
    // 逆向解析
    getChangeAddress(status, result) {
      if (status === 'complete' && result.info === 'OK') {
        const { formattedAddress = '' } = result.regeocode
        this.location.address = formattedAddress
        document.getElementById('tipsinput').value = `${formattedAddress}`
        this.$emit('input', this.location)
      }
    },
    handler() {
      return {
        initMap: () => {
          // 初始化地图对象，加载地图
          AMapLoader.load({
            key: 'caf024434f22d41c39de56bae55c8cee', // 申请好的Web端开发者Key，首次调用 load 时必填
            // 'securityJsCode': 'bca27b469a3ea657b4dae593073ac263', // 安全密钥
            version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: [
              'AMap.AutoComplete', // 输入提示
              'AMap.PlaceSearch', // 地点搜索服务
              'AMap.Geocoder' // 地理编码与逆地理编码
            ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            AMapUI: { // 是否加载 AMapUI，缺省不加载
              'version': '1.1', // AMapUI 版本
              'plugins': ['overlay/SimpleMarker'] // 需要加载的 AMapUI ui插件
            },
            Loca: { // 是否加载 Loca， 缺省不加载
              'version': '2.0' // Loca 版本
            }
          }).then((AMap) => {
            var map = ''
            if (this.value.lat && this.value.lng) {
              map = new AMap.Map('containerMap', {
                resizeEnable: true,
                zoom: 15,
                center: [this.value.lng, this.value.lat]
              })
              console.log('地图复赋值', this.value)
              this.location = this.value
              document.getElementById('tipsinput').value = `${this.value.address}`
              document.getElementById('lnglat').value = `${this.value.lng},${this.value.lat}`
            } else {
              map = new AMap.Map('containerMap', {
                resizeEnable: true,
                zoom: 15
              })
            }
            // 地理编码与逆地理编码
            this.geocoder = new AMap.Geocoder()
            // 绑定地图点击事件
            map.on('click', this.clickHandler)
            // 输入提示
            const auto = new AMap.AutoComplete(this.autoOptions)
            this.placeSearch = new AMap.PlaceSearch({
              map
            })
            // 构造地点查询类
            auto.on('select', this.mapSelect)
          }).catch(e => {
            console.error('错误信息', e)
          })
        }
      }
    }

  }
}
</script>
<style scoped>
.container{
  display: flex;
  flex-direction: column;
  /* flex-direction: row; */
  height: 500px !important;
  position: relative;
}
#containerMap{
  flex: 1;
  left: unset;
  width: 100%;
  /* height: 90%; */
}
.amap-copyright {
  bottom: 9px ;
}
.map-container {
  position: absolute;
  top: 20px;
  right: 15%;
  display: flex;
  flex-shrink: 0;
  width: 70%;
  background: #fff;
}
.map-item1 {
  flex: 2;
  margin-left: 5px;
}
.map-item2 {
  flex: 1;
  margin-left: 5px;
  margin-right: 5px;
}
.map-item1 input, .map-item2 input{
  height: 25px;
}
::v-deep .amap-sug-result {
  z-index: 9999;
  visibility:visible;
}
#tipsinput, #lnglat {
  width: 100%;
  position: relative;
  top: -5px;
}
</style>
